package com.lemon.boot.service.impl;

import cn.hutool.core.lang.Dict;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lemon.boot.common.base.BaseServiceImpl;
import com.lemon.boot.common.enums.DeleteEnum;
import com.lemon.boot.common.enums.StatusEnum;
import com.lemon.boot.common.exception.CustomException;
import com.lemon.boot.common.utils.ObjectFieldUtil;
import com.lemon.boot.common.utils.ValidateUtil;
import com.lemon.boot.common.web.Result;
import com.lemon.boot.dao.TenantDAO;
import com.lemon.boot.dto.TenantDTO;
import com.lemon.boot.po.TenantPO;
import com.lemon.boot.service.ITenantService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 租户表 业务实现类
 *
 * @author Lemon
 * @since 2024-02-29
 */
@Log4j2
@Service
public class TenantServiceImpl extends BaseServiceImpl<TenantDAO, TenantPO, TenantDTO> implements ITenantService {
    @Override
    public Page<TenantPO> page(TenantDTO tenantDTO) {
        tenantDTO.setDeleted(DeleteEnum.UNABLE.getDeleted());
        return this.baseMapper.page(tenantDTO);
    }

    @Override
    @Transactional
    public TenantPO register(TenantPO tenantPO) {
        //1.判断输入的值是否正确
        Result<String> result = ObjectFieldUtil.isNull(tenantPO, "fullName", "abbName", "startDate", "endDate", "legalPerson", "licenseNumber", "socialCode", "provinceId", "cityId", "countyId", "address");
        if (!result.isSuccess()) {
            throw new CustomException(result.getMessage());
        }
        if (tenantPO.getLicenseNumber().length() <= 12) {
            throw new CustomException(String.format("证照编号\"%s\"过短！", tenantPO.getLicenseNumber()));
        }
        if (tenantPO.getSocialCode().length() <= 17) {
            throw new CustomException(String.format("社会统一信用代码\"%s\"过短！", tenantPO.getSocialCode()));
        }
        if (!ValidateUtil.isTel(tenantPO.getPhone()) && !ValidateUtil.isPhone(tenantPO.getPhone())) {
            throw new CustomException("公司电话错误！");
        }

        //2.判断租户名称是否重复
        boolean tenantExist = this.query().select("1")
                .eq("full_name", tenantPO.getFullName()).last("limit 1").exists();
        if (tenantExist) {
            throw new CustomException("公司名称已存在，请确认！");
        }

        //5.添加租户信息
        this.save(tenantPO);
        return tenantPO;
    }
}